import axios from 'axios'
import {Message, MessageBox} from "element-ui";

const configMG = require('../../config/config.js')
// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// axios.defaults.headers['x-token'] = localStorage.getItem('x-token');

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "/",
  // 超时
  timeout: 60000
});

let loading;

// request拦截器
service.interceptors.request.use(config => {
  // if(!config.headers.hasOwnProperty("x-token") && !configMG.isLogin) {
  //   configMG.isLogin = true;
  //   // window.location.href = "http://127.0.0.1:18888/api/auth/sso/auth?redirect=" + window.location.href;
  // }

  config.headers['Content-Type'] = 'application/json; charset=UTF-8';
  return config;
}, error => {
  Promise.reject(error)
});


service.interceptors.response.use(res => {
    if (res.config.responseType === 'blob') {
      return res;
    }
    let result = res.data;
    result.success = result.code === 200;
    if (result.code === 401 && !configMG.isLogin) {
      setTimeout(function () {
        Message.error("未登录或缺少操作必要的操作权限");
      }, 1000);
      let cookies = document.cookie.split(";");
      for (let i = 0; i < cookies.length; i++) {
        let coo = cookies[i];
        if(coo.indexOf("x-token") > -1) {
          window.location.href = document.location.protocol + "//" + document.domain + document.location.port + document.URL.substring(document.URL.lastIndexOf("#"), document.URL.length)
        }
      }
      window.location.href = configMG.loginPage + "?&redirect=" + window.location.href;
      // window.location.href = document.location.protocol + "//" + document.domain + document.location.port + document.URL.substring(document.URL.lastIndexOf("#"), document.URL.length)
    }
    if (result.code === 500) {
      Message.error(res.data.msg);
      return Promise.reject(res.data.msg);
    }
    return result;
  },
  error => {
    if (error.response.status === 401 && !configMG.isLogin) {
      configMG.isLogin = true;
      window.location.href = configMG.loginPage + "?redirect=" + window.location.href;
    }
    return Promise.reject(error)
  }
);

export default service
